#!/usr/bin/env python

import subprocess
import os
from utils.singleton import singleton
from conf import Conf
import sys
import time
#from conf import ServerConf




DATABASE_PATH="database/"
DATABASE_CONF="conf/database/"


@singleton
class Databases:
    def __init__(self):
        self.dir=DATABASE_PATH
        self._pipe=None
        self._databases=[]
        
        list=os.listdir(self.dir)
        
        #s=Server("All","Server")
        #self._databases.append(s)
        
        for name in list:
            d=Database(name,self.dir+'/'+name)
            self._databases.append(d)

        self._currentServer=self._databases[0]
        
        #self.cmdStop="httpd.exe"
    
    def start(self):
        self._currentServer.start()
    
    def stop(self):
        self._currentServer.stop()
        #if self._pipe:
        #    self._pipe.terminate()

    def getDatabaseList(self):
        return self._databases
    
    def getCurrentDatabase(self):
        return self._currentServer
    
    def getServerByName(self,name):
        for server in self._databases:
            if server.name==name:
                return server
    
    #def getEnableServer(self):
    #    return self._databases
  
  
  
    
class Database:
    def __init__(self,name="",path=""):
        self._pipe=None
        self.name=name
        self.path=path
        self._cmdStart="bin/httpd.exe"
        self.node=-1;
        self.paths={}
        paths=Conf().getServerPaths(self.name);
        for path in paths:
            self.addPath(paths[path],path)
        self._conf=DatabaseConf(self)
        #self.addPath('www','www')
        self.setDocumentRoot(Conf().getServerRoot(self.name))
        
    
    def start(self):
        self._conf.apply()
        cmd=self._cmdStart.split(" ")
        path=cmd[0].split("/")
        cmd=[path[-1]]+cmd[1:]
        path="/".join(path[0:-1])
        self._pipe=execCmd(self.path+"/"+path,cmd)
        print "start:"+self.name
    
        
    def stop(self):
        if self._pipe:
            #os.kill( self._pipe, 9 )
            self._pipe.kill()
            #self._pipe.wait()
            self._pipe=None
            print "stop:"+self.name
            #cleanup(self._pipe)
            
    
    def addPath(self,name,path):
        self.paths[self.convertPath(path)]=name
    
    def removePath(self,path):
        del self.paths[self.convertPath(path)]
        print(self.paths)
    
    def getPaths(self):
        return self.paths
        
    def setDocumentRoot(self,path):
        self.documentRoot=self.convertPath(path)
        
    def getDocumentRoot(self):
        return self.documentRoot
    
    def convertPath(self,path):
        return os.path.abspath(path).replace("\\","/")
    
    def getServerConf(self):
        return self._conf
    


class DatabaseConf:
    def __init__(self,server):
        self.server=server
        self.dir=DATABASE_CONF
        self._conf="dev"
        
    
    def _readData(self):
        pass
    
    def apply(self):
        self.readFolder(self.dir+self._conf+'/'+os.path.basename(self.server.path))
    
    def readFolder(self,folder):
        dirs=os.listdir(folder);
        for element in dirs:
            path=folder+'/'+element 
            if os.path.isdir(path):
                self.readFolder(path)
            else:
                self.readfile(path)
    
    def readfile(self,file):
        data=open(file,"r").read()
        
        data,virtualServer=self.getBlock(data,"VirtualServeur_TMP",True)
        
        
        paths=self.server.getPaths()
        for path in paths:
            result=self.replaceTag(virtualServer,{"VirtualPath":self.server.convertPath(path), "VirtualName":paths[path]})
            data=self.addDataBetween("VirtualServeur",data,result)
        data=self.replaceTag(data)
        
        path=file[file.find(self._conf)+len(self._conf)+1:]
        open(SERVER_PATH+path,"w+").write(data)
        
    def addDataBetween(self,tag,old,add):
        tag="{{"+tag+"}}"
        startPos=old.find(tag)+len(tag)+1
        old=old[:startPos]+add+old[startPos:]
        return old
        
        
    def replaceTag(self,data,tags={}):
        data=data.replace("${server_path}",os.path.abspath('.').replace("\\","/")+'/'+"Server")
        data=data.replace("${root_path}",self.server.getDocumentRoot())
        
        for tag in tags:
            data=data.replace("${"+tag+"}",tags[tag])
        
        return data
        
        
    def getBlock(self,data,tag,delete=False):
        start=data.find("{{"+tag+"}}")
        end=data.find("{{/"+tag+"}}",start)
        block=data[start+len("{{"+tag+"}}"):end]
        data=data[0:start]+data[end+len("{{/"+tag+"}}"):]
        return (data,block)
        
    
    def getConfigsAvailable(self):
        list=os.listdir(self.dir)
        ret=[]
        for dir in list:
            if(os.path.isdir(self.dir+dir)):
                ret.append(dir)
        return ret
    
    def getDefaultConfig(self):
        return self._conf
        
    def setDefaultConfig(self,dir):
        self._conf=dir


    
    
def execCmd(folder,arg):
    print folder
    folder=os.path.abspath(folder)
    pipe = subprocess.Popen(arg, stdout=subprocess.PIPE,cwd=folder,shell=True)
    return pipe    